package com.neusoft.admin.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.neusoft.admin.entity.provinceId;
import com.neusoft.admin.entity.provinceList;
import com.neusoft.grid.entity.AQI;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.geometry.Pos;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;

public class provinceItemViewControl {
    @FXML
    private TableView<provinceList> tableView;
    @FXML
    private ObservableList<provinceList> dataList = FXCollections.observableArrayList();
    @FXML
    private TableColumn<provinceList, Integer> idColumn, provinceShortColumn, provinceColumn, AQIOutTatalColumn,
            SO2OutTatalColumn, COOutTatalColumn, PMOutTatalColumn;
    private Map<Integer, provinceList> map = new HashMap<>();
    private Map<String, provinceId> provinceIdMap = new HashMap<>();
    private int id;
    private String provinceForShort;
    private String provinceName;
    private int AQIOutTatal;
    private int SO2OutTatal;
    private int COOutTatal;
    private int PMOutTatal;

    private static final String AQI_FILE = "src/com/neusoft/grid/data/AQI.txt";

    @FXML
    public void initialize() throws IOException {
        readProvinceId();
        reader();
        setTable();
    }

    public void setTable() {
        setupColumn(idColumn, "id");
        setupColumn(provinceShortColumn, "provinceForShort");
        setupColumn(provinceColumn, "name");
        setupColumn(AQIOutTatalColumn, "AQIOutTatal");
        setupColumn(SO2OutTatalColumn, "SO2OutTatal");
        setupColumn(COOutTatalColumn, "COOutTatal");
        setupColumn(PMOutTatalColumn, "PMOutTatal");
        idColumn.setSortable(false);
        provinceShortColumn.setSortable(false);
        provinceColumn.setSortable(false);
        AQIOutTatalColumn.setSortable(false);
        SO2OutTatalColumn.setSortable(false);
        COOutTatalColumn.setSortable(false);
        PMOutTatalColumn.setSortable(false);
        dataList.addAll(map.values());
        tableView.setItems(dataList);
    }

    public void reader() {
        try {
            File file = new File("src/com/neusoft/admin/data/mission.txt");
            List<AQI> aqiList = loadAQIData();
            try (BufferedReader br = new BufferedReader(new FileReader(file))) {
                if (!file.exists()) {
                    System.out.println("文件不存在");
                    return;
                }
                String line;
                int i = 0;
                // 用于存储每个省份的统计信息，键为省份ID，值为 provinceList 对象
                Map<Integer, provinceList> provinceStats = new HashMap<>();
                while ((line = br.readLine()) != null) {
                    if (i >= aqiList.size()) {
                        break;
                    }
                    String[] parts = line.split(" ");
                    provinceName = parts[6];
                    if (provinceIdMap.containsKey(provinceName)) {
                        id = provinceIdMap.get(provinceName).getId();
                        provinceForShort = provinceIdMap.get(provinceName).getProvinceForShort();
                        AQI aqiData = aqiList.get(i);

                        // 若该省份还未在统计中，创建新的 provinceList 对象i
                        provinceList pList = provinceStats.computeIfAbsent(id,
                                k -> new provinceList(id, provinceForShort, provinceName, 0, 0, 0, 0));

                        // 统计 AQIOutTatal
                        if (aqiData.getAQI() > 100) {
                            pList.setAQIOutTatal(pList.getAQIOutTatal() + 1);
                        }
                        // 统计 SO2OutTatal
                        if (aqiData.getSO2() > 150) {
                            pList.setSO2OutTatal(pList.getSO2OutTatal() + 1);
                        }
                        // 统计 COOutTatal
                        if (aqiData.getCO() > 10) {
                            pList.setCOOutTatal(pList.getCOOutTatal() + 1);
                        }
                        // 统计 PMOutTatal
                        if (aqiData.getPM() > 75) {
                            pList.setPMOutTatal(pList.getPMOutTatal() + 1);
                        }
                    }
                    i++;
                }
                // 将统计结果放入 map 中
                map.clear();
                map.putAll(provinceStats);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private <T> void setupColumn(TableColumn<provinceList, T> column, String property) {
        column.setCellValueFactory(new PropertyValueFactory<>(property));
        column.setCellFactory(col -> new TableCell<>() {
            @Override
            protected void updateItem(T item, boolean empty) {
                super.updateItem(item, empty);
                if (empty || item == null) {
                    setText(null);
                } else {
                    setText(item.toString());
                }
                // 设置单元格内容居中显示
                setAlignment(Pos.CENTER);
            }
        });
    }

    private List<AQI> loadAQIData() throws IOException {
        File file = new File(AQI_FILE);
        if (!file.exists() || file.length() == 0) {
            return new ArrayList<>();
        }

        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
            return (List<AQI>) ois.readObject();
        } catch (ClassNotFoundException e) {
            throw new IOException("数据文件格式错误", e);
        }
    }

    public void readProvinceId() throws IOException {
        File file = new File("src/com/neusoft/admin/data/provinceId.txt");

        if (!file.exists()) {
            System.out.println("文件不存在");
            return;
        }
        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = br.readLine()) != null) {
                // 按逗号分割每行数据
                String[] parts = line.split(",");
                if (parts.length == 3) {
                    String name = parts[0];
                    int id = Integer.parseInt(parts[1]);
                    String forShort = parts[2];
                    provinceId pId = new provinceId(id, name, forShort);
                    provinceIdMap.put(name, pId);
                }
            }
        }
    }
}
